package com.wallet.crypto.trustapp.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;

import com.google.android.gms.flags.IFlagProvider;
import com.wallet.crypto.trustapp.R;
import com.wallet.crypto.trustapp.util.Loger;

/**
 * Created by lingjianzhong on 2018/5/10.
 */

@SuppressLint("AppCompatCustomView")
public class GradientColorTextView extends TextView{
    private LinearGradient mLinearGradient;
    private Paint mPaint;
    private int mViewWidth = 0;
    private Rect mTextBound = new Rect();

    private int mTileMode = 0;
    private int mStartColor = Color.parseColor("#616161");
    private int mEndColor = Color.parseColor("#616161");

    private Shader.TileMode mShaderTileMode;

    public GradientColorTextView(Context context) {
        this(context,null);
    }

    public GradientColorTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public GradientColorTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.GradientColorTextView);
        int n = array.getIndexCount();
        Loger.e(" a.getIndexCount() " + n);
        for(int i = 0; i < n; i++){
            int attr = array.getIndex(i);
            if (attr == R.styleable.GradientColorTextView_TileMode){
                mTileMode = array.getInt(attr,mTileMode);
            }else if (attr == R.styleable.GradientColorTextView_StartColor){
                mStartColor = array.getColor(attr,mStartColor);
            }else if (attr == R.styleable.GradientColorTextView_EndColor){
                mEndColor = array.getColor(attr,mEndColor);
            }
        }
        if (array!=null)
            array.recycle();

        initSetting();
    }

    private void initSetting() {
      if (mTileMode == 1){
          mShaderTileMode = Shader.TileMode.REPEAT;
      }else if (mTileMode == 2){
          mShaderTileMode = Shader.TileMode.MIRROR;
      }else {
          mShaderTileMode = Shader.TileMode.CLAMP;
      }
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            mLinearGradient =new LinearGradient(
                    0, 0, getWidth(), getHeight(),
                    new int[]{mStartColor, mEndColor}, null,
                    Shader.TileMode.CLAMP);
            getPaint().setShader(mLinearGradient);
        }
    }
}
